# -*- coding: UTF-8 -*-

import pymysql

import common.Logger as Logger
from common.Constants import *

logger = Logger.get_logger(__name__)

def connect_db():
    logger.info('---MySQL_CONNECTING---连接到mysql服务器...---MySQL_CONNECTING---')
    db = pymysql.connect(host = mysql_host, port = mysql_port, user = mysql_user,
                         passwd = mysql_password, db = mysql_db, charset=mysql_encode)
    logger.info("---MySQL_CONNECTED---数据库已连接---MySQL_CONNECTED---")
    return db

def get_cursor(db):
    return db.cursor()

def close_db(db):
    db.close()

def select(sql):
    logger.debug("---MySQL_SQL---准备执行的SQL语句： " + sql)

    db = connect_db()
    cursor = get_cursor(db)

    try:
        cursor.execute(sql)
    finally:
        close_db(db)

    if cursor.rowcount <= 0:
        logger.error("---NO_DATA---没有查询到数据---NO_DATA---")
        return ()
    else:
        return cursor._rows